let app = getApp()
const util = require('../../utils/util.js')
import { request } from "../../utils/request.js";
Page({
    data: {
        userId: 0,
        currentDate: new Date().getTime(),
        maxDate: new Date().getTime(),
        minDate: 0,
        write_min_date: Date.now() - 60 * 60 * 24 * 1000 * 365 * 5,
        pop_show: false,
        pop_kind: false,
        pop_write: false,

        month: '',
        year: '',
        listForDay: [],
        income: 0,
        outcome: 0,
        showKindName: "全部类型",
        user_all_kind: [],
        configColor: app.globalData.configColor,
        yuejieyu: 0,
        selected: [],
        groupName: '',
        detail_show: false,
        selectedGroupName: '',
        selectedMoney: '',
        selectedDate: '',
        selectedRemark: '',
        selectedUserName: '',
        keyCodeForSearch: '',
        showAddButton: true,
        billPart: 0,

        showMask: false,
        statusBarHeight: app.globalData.statusBarHeight,
        navBarHeight: app.globalData.navBarHeight
    },
    changeBillPart(e) {
        if (this.selectComponent('#loginPopup').init()) {
            return
        }
        let partNum = e.currentTarget.dataset.billpartnum
        if (partNum == 0) {
            this.setData({
                billPart: 0
            });
        } else {
            this.setData({
                billPart: this.data.billPart == partNum ? 0 : partNum
            });
        }
        this.show()
    },
    go_group() {
        if (this.selectComponent('#loginPopup').init()) {
            return
        }
        wx.navigateTo({
            url: '/pages/group/group',
        })
    },
    // 关闭弹出
    onClose() {
        this.setData({
            pop_show: false,
            pop_kind: false,
            pop_write: false,
            detail_show: false,

            selectedGroupName: '',
            selectedMoney: '',
            selectedDate: '',
            selectedRemark: '',
            selectedUserName: ''
        });
    },
    // 滑动块
    onTap() {//这是点击其他区域时，根据id让当前打开的元素关闭
        // this.data.selected.forEach(function (instance) {
        //       instance.close();
        //     });

        let instance = this.selectComponent("#" + this.data.selected + "");
        if (instance != null) { instance.close(); }
    },
    onCloseSwipe(event) {
        const { position, instance } = event.detail;
        // console.log(position)
        // switch (position) {
        //   case 'cell':
        //     instance.close();
        //     break;
        //   case 'right':
        //     Dialog.confirm({
        //       message: '确定删除吗？',
        //     }).then(() => {
        //       instance.close();
        //     });
        //     break;
        // }   
        event.detail.instance.close();
    },
    onOpenSwipe(event) {
        // 根据id选择instance
        // let instance = this.selectComponent(`#${event.target.id}`);
        // this.data.selected.push(instance);
        this.setData({
            selected: event.currentTarget.id
        })
    },
    // onTap() {
    // console.log(this.data.selected);
    // // 循环关闭
    // this.data.selected.forEach(function (instance) {
    //   instance.close();
    // });
    // // 清空
    // this.data.selected = [];
    //   },

    // 删除单条记录
    delRecord(e) {
        if (e.currentTarget.dataset.userid != wx.getStorageSync('userInfo').id) {
            wx.showToast({
                title: '禁止删除他人账单',
                icon: 'none'
            })
            return
        }

        wx.request({
            url: app.globalData.url + '/delBill',
            method: 'GET',
            data: {
                id: e.currentTarget.dataset.delid,
                optionUserId: wx.getStorageSync('userInfo').id,
                userId: e.currentTarget.dataset.userid
            },
            success: (res) => {
                let re = res.data.flag
                if (re) {
                    wx.showToast({
                        title: '删除成功',
                        icon: 'none'
                    })
                    this.show()
                } else {
                    wx.showToast({
                        title: '删除失败: ' + res.data.message,
                        icon: 'none'
                    })
                }
            },
            fail: (err) => {
                wx.showToast({
                    title: '删除失败，请稍后尝试',
                    icon: 'none'
                })
            }
        })
    },

    // 开启弹窗
    showPopup() {
        if (this.selectComponent('#loginPopup').init()) {
            return
        }
        this.setData({
            pop_show: true,
            pop_kind: false,
            pop_write: false,
            detail_show: false
        });
    },
    // 记一笔
    showPopup_write() {
        if (this.selectComponent('#loginPopup').init()) {
            return
        }
        wx.navigateTo({
            url: "/pages/add_record/add_record",
        });
    },
    // 开启类型选择弹窗
    showPopup_kind() {
        if (this.selectComponent('#loginPopup').init()) {
            return
        }
        this.setData({
            pop_kind: true,
            pop_show: false,
            pop_write: false,
            detail_show: false
        })
    },

    // 查询用户指定类型数据
    choose_kind(e) {
        wx.showLoading({
            title: '数据加载中',
        })
        let that = this
        let index = e.currentTarget.dataset.index * 1
        let year = that.data.year
        let month = that.data.month
        that.get_show_list(year, month, index)
        that.setData({
            pop_kind: false
        })
    },

    // 年月选择
    async chooseDate(event) {
        let date = new Date(event.detail);
        // let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
        this.setData({
            pop_show: false,
            year: date.getFullYear(),
            month: date.getMonth() + 1,
            currentDate: event.detail
        })
        app.globalData.cache_year_index = this.data.year
        app.globalData.cache_month_index = this.data.month
        // 获取当月账单的所有类别
        await this.getBillAllCategory()
        this.show()
    },
    go_edit(e) {
        if (e.currentTarget.dataset.record.userId != wx.getStorageSync('userInfo').id) {
            wx.showToast({
                title: '禁止修改他人账单',
                icon: 'none'
            })
            return
        }
        let billId = e.currentTarget.dataset.record.id
        let money = e.currentTarget.dataset.record.money
        let isOut = e.currentTarget.dataset.record.isOut
        let remark = e.currentTarget.dataset.record.remark
        //   let createTime = new Date(e.currentTarget.dataset.createtime).getTime()
        let createTime = e.currentTarget.dataset.record.createTime
        let categoryId = e.currentTarget.dataset.record.categoryId
        wx.navigateTo({
            url: "/pages/add_record/add_record?billId=" + billId + "&money=" + money + "&isOut=" + isOut + "&createTime=" + createTime + "&categoryId=" + categoryId + "&remark=" + remark
        })
    },
    show_one_category(e) {
        let choosekindname = e.currentTarget.dataset.choosekindname;
        this.setData({
            showKindName: choosekindname,
            pop_kind: false
        })
        this.show()
    },
    onTapAndOpenDetail(e) {
        this.onTap();
        let detail = e.currentTarget.dataset.detail
        // console.log(detail)
        let money = ''
        if (detail.isOut) {
            money = detail.money + ' (支出)'
        } else {
            money = detail.money + ' (收入)'
        }
        this.setData({
            pop_show: false,
            pop_kind: false,
            pop_write: false,
            detail_show: true,

            selectedGroupName: detail.categoryName,
            selectedMoney: money,
            selectedDate: detail.createTime,
            selectedRemark: detail.remark,
            selectedUserName: detail.username,
        })
    },
    changeSearch(e) {
        if (this.selectComponent('#loginPopup').init()) {
            return
        }
        this.setData({
            keyCodeForSearch: e.detail,
        });
    },
    clearSearch() {
        this.setData({
            keyCodeForSearch: '',
        });
        this.onSearch();
    },
    focusSearch() {
        this.setData({
            showMask: true,
        });
    },
    onSearch() {
        if (this.selectComponent('#loginPopup').init()) {
            return
        }
        this.show()
    },
    async getBillAllCategory() {
        // 获取当月账单的所有类别
        const categoryList = await request({
            url: '/getBillAllCategory',
            method: 'POST',
            header: { 'content-type': 'application/json' },
            data: {
                userId: wx.getStorageSync('userInfo').id,
                year: this.data.year,
                month: this.data.month,
                groupId: wx.getStorageSync('userInfo').groupVO.id
            }
        })
        let currentKindName = '全部类型'
        for (let index = 0; index < categoryList.length; index++) {
            const element = categoryList[index];
            if (element.name == this.data.showKindName) {
                currentKindName = this.data.showKindName;
                break;
            }
        }
        this.setData({
            showKindName: currentKindName,
            user_all_kind: categoryList,
        })
    },
    show() {
        wx.showLoading({
            title: '',
        })
        // 获取数据
        wx.request({
            url: app.globalData.url + '/getBill',
            method: 'POST',
            header: {
                'content-type': 'application/json'
            },
            data: {
                userId: wx.getStorageSync('userInfo').id,
                year: this.data.year,
                month: this.data.month,
                categoryName: this.data.showKindName == '全部类型' ? '' : this.data.showKindName,
                groupId: wx.getStorageSync('userInfo').groupVO.id,
                searchKey: this.data.keyCodeForSearch,
                billPart: this.data.billPart
            },
            success: (res) => {
                let responseData = res.data
                this.setData({
                    listForDay: responseData.data,
                    outcome: 0,
                    income: 0,
                    yuejieyu: 0,
                    showMask: false
                })
                if (responseData.data.length > 0) {
                    this.setData({
                        outcome: responseData.data[0].outForMonth,
                        income: responseData.data[0].inForMonth,
                        yuejieyu: responseData.data[0].remainForMonth,
                    })

                }
                wx.hideLoading()
            },
            fail: (err) => {
                console.log('失败', err);
            }
        })
    },
    onLoad: function (options) {
        wx.hideShareMenu({
            menus: ['shareAppMessage', 'shareTimeline']
        })
    },
    onShow: function () {
        // 登录弹窗
        if (this.selectComponent('#loginPopup').init()) {
            return
        }
        // 切换主题颜色
        if (wx.getStorageSync('configColor') !== this.data.configColor) {
            this.setData({ configColor: wx.getStorageSync('configColor') });
        }
        this.onClose()
        let groupNameTemp = wx.getStorageSync('userInfo').groupVO.name
        this.setData({
            userId: wx.getStorageSync('userInfo').id,
            groupName: groupNameTemp ? groupNameTemp : '默认账本',
            outcome: 0,
            income: 0,
            yuejieyu: 0,
            // showKindName: '全部类型',
        })

        // 获取账本状态
        wx.request({
            url: app.globalData.url + '/getGroupStatus',
            method: 'GET',
            data: {
                userId: wx.getStorageSync('userInfo').id,
                groupId: wx.getStorageSync('userInfo').groupVO.id
            },
            success: (res) => {
                if (res.data.data == 2) {
                    this.setData({
                        showAddButton: true,
                    })
                } else {
                    this.setData({
                        showAddButton: false,
                    })
                }
                if (this.data.showAddButton && app.globalData.loginToAdd == 1) {
                    wx.navigateTo({
                        url: '/pages/add_record/add_record',
                    })
                } else {
                    if (!this.data.showAddButton) {
                        app.globalData.loginToAdd = 0
                    }
                    var flag = true;
                    if (app.globalData.cache_year_index > 0 && app.globalData.cache_month_index > 0) {
                        flag = false;
                        this.setData({
                            year: app.globalData.cache_year_index,
                            month: app.globalData.cache_month_index,
                        })
                    }
                    // 获取最早+最晚记录时间
                    wx.request({
                        url: app.globalData.url + '/getDateRangeByGroup',
                        method: 'POST',
                        header: { 'content-type': 'application/json' },
                        data: {
                            groupIdList: [wx.getStorageSync('userInfo').groupVO.id]
                        },
                        success: (res) => {
                            let responseData = res.data
                            this.setData({
                                minDate: responseData.data.minDateStamp,
                                maxDate: responseData.data.maxDateStamp
                            })
                            if (flag) {
                                var date = new Date();
                                var maxRecordDate = new Date();
                                if (responseData.data.maxDateStamp) {
                                    maxRecordDate = new Date(responseData.data.maxDateStamp);
                                }
                                if (maxRecordDate < date) {
                                    date = maxRecordDate
                                }
                                // if (responseData.data.maxDateStamp == null) {
                                //     date = new Date();
                                // } else {
                                //     date = new Date(responseData.data.maxDateStamp);
                                // }
                                this.setData({
                                    year: date.getFullYear(),
                                    month: date.getMonth() + 1,
                                    // currentDate: responseData.data.maxDateStamp
                                    currentDate: date.getTime()
                                })
                                app.globalData.cache_year_index = this.data.year
                                app.globalData.cache_month_index = this.data.month
                            } else {
                                this.setData({
                                    currentDate: new Date(app.globalData.cache_year_index + "/" + app.globalData.cache_month_index).getTime()
                                })
                            }
                            // 获取当月账单的所有类别
                            this.getBillAllCategory()
                            this.show()
                        },
                        fail: (err) => {
                            console.log('失败', err);
                        }
                    })
                }
            }
        })

    }

})



